<?php

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\common\controller\AdminController;
use app\common\model\BusinessDistrict;
use app\common\model\GoodsSku;
use app\common\model\PointsLog;
use app\common\model\ShopManage;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\facade\Db;
use think\helper\Str;

/**
 * @ControllerAnnotation(title="店铺表")
 */
class Shop extends AdminController
{

    use \app\admin\traits\Curd;

    protected $allowModifyFields
        = [
            'platform_goods_switch',
            'share_goods_switch',
        ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\Shop();


    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $districtId = input('district_id', 0, 'intval');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            //var_dump($where);
//            if ($districtId) {
//                $where[] = ['district_id', '=', $districtId];
//            }
//            if ($this->user['role'] == 1) {
//                $shopIds = \app\common\model\Shop::where('user_id', $this->user['id'])->column('id');
//                if ($shopIds) {
//                    $where[] = ['id', 'in', $shopIds];
//                }
//            }
            $count = $this->model
                ->alias('s')
                ->where($where)
                ->leftJoin('pm_business_district bd', 's.district_id = bd.id')
                ->count();
            $list  = $this->model
                ->alias('s')
                ->where($where)
                ->leftJoin('pm_business_district bd', 's.district_id = bd.id')
                ->leftJoin('pm_user u', 's.user_id = u.id')
                ->page($page, $limit)
                ->order('s.status', 'desc')
                ->order('points_one', 'asc')
                ->field('s.*,bd.name as district_name,u.nickname')
                ->select();
            foreach ($list as $k => $v) {
                if ($v->district_id == 0) {
                    $v->district_name = '无';
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('district_id', $districtId);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            Db::startTrans();
            try {
                /* $admin = SystemAdmin::where('username', $row['phone'])->find();
                 if (!$admin) {//如果没有管理员，添加管理员
                     $admin = SystemAdmin::create([
                         'username' => $row['phone'],
                         'auth_ids' => 7,
                         'phone' => $row['phone'],
                         'password' => password($row['phone'])
                     ]);
                 } else {//如果管理员存在

                 }*/

                \app\common\model\Shop::where('id', $id)->update($post);
                $adminStatus = 0;
//                switch ($row['status']) {
//                    case 1://已审核通过
//                        $adminStatus = $post['status'] != 1 ? 0 : 1;
//                        break;
//                    case 2://已关店
//                        $adminStatus = $post['status'] == 1 ? 1 : 0;
//                        break;
//                    default://待审核
//                        $adminStatus = $post['status'] == 1 ? 1 : 0;
//                        break;
//                }
//                $adminId = \app\common\model\User::where('id', $row['user_id'])->value('admin_id');
//                if ($adminStatus == 1) {
//                    if (!$adminId) {
//                        throw new \Exception('管理员账号错误');
//                    }
//                } else {
//                    // $adminId =
//                }
//
//                SystemAdmin::where('id', $adminId)->update([
//                    'status' => $adminStatus
//                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
            $this->success('保存成功');
        }
        $district = BusinessDistrict::where([])->field('name,id')->select()->toArray();
        $this->assign('district', $district);
        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="编辑")
     * 设置商圈
     */
    public function edit1($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'district_id' => 'require'
            ];
            $this->validate($post, $rule);
            //判断当前店铺 在当前商圈中 是否已经结算完成
            $shop = \app\common\model\Shop::find($id);
            if ($shop->points_one != 0) {
                $this->error('当前店铺在商圈中未结算,暂不能更换商圈');
            }
            Db::startTrans();
            try {
                \app\common\model\Shop::where('id', $id)->update(['district_id' => $post['district_id']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
            $this->success('保存成功');
        }
        $district = BusinessDistrict::select();
        $this->assign('district', $district);
        $this->assign('row', $row);
        return $this->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'phone' => 'require',
            ];
            $this->validate($post, $rule);

            $user = \app\common\model\User::where('phone', $post['phone'])->find();
            if (!$user) {
                $this->error('当前手机号用户不存在');
            }

            Db::startTrans();
            try {
                $userId          = $user->id;
                $post['user_id'] = $userId;
                if (isset($post['file'])) {
                    unset($post['file']);
                }
                if (!$post['shop_code']) {
                    $post['shop_code'] = Str::random(6, 2);
                }
                $shop = \app\common\model\Shop::create($post);
                ShopManage::create([
                    'user_id'      => $userId,
                    'shop_id'      => $shop->id,
                    'role'         => 1,
                    'function_arr' => '1,2,3,4',
                    'status'       => 1,
                    'remark'       => '后台生成店铺'
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败:' . $e->getMessage());
            }
            $shop ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    public function list()
    {
        $page     = input('page', 1, 'intval');
        $pageSize = input('page_size', 15, 'intval');
        $keyword  = input('keyword', '', 'trim');
        $selected = input('selected', '', 'trim');
        $exclude  = input('exclude', '', 'trim');
        $where    = [];

        if ($keyword) {
            $where[] = ['name', 'like', "%$keyword%"];
        }
        if ($exclude) {
            $where[] = ['id', 'not in', explode(',', $exclude)];
        }
        $list       = \app\common\model\Shop::where($where)->field('name,id as value');
        $totalCount = $list->count();
        $totalPage  = ceil($totalCount / $pageSize);

        if ($selected) {
            $list = $list->orderRaw('field(id,' . $selected . ') desc');
        }
        $list = $list->order('id desc')->page($page, $pageSize)->select()->toArray();
        foreach ($list as $k => $l) {
            if (in_array($l['value'], explode(',', $selected))) {
                $list[$k]['selected'] = true;
            }
        }
        return $this->success('', ['list' => $list, 'total_page' => $totalPage]);
    }

    /**
     * 结算页面 数据展示
     * 以及数据结算
     */
    public function settlement($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            if ($row->points_one == 0) {
                $this->error('当前店铺不需要结算');
            }
            Db::startTrans();
            try {
                $num = $row->points_one;
                //店铺增加积分变动记录
                if ($num < 0) {
                    //需要补充店铺积分
                    //商户增加积分记录
                    PointsLog::create([
                        'form_user_id'   => 0,
                        'user_id'        => 0,
                        'shop_id'        => $row->id,
                        'num'            => -$num,
                        'type'           => 4,
                        'flag'           => 3,
                        'relation_id'    => 0,
                        'relation_sheet' => 0,
                    ]);
                } else {
                    PointsLog::create([
                        'form_user_id'   => 0,
                        'user_id'        => 0,
                        'shop_id'        => $row->id,
                        'num'            => $num,
                        'type'           => 5,
                        'flag'           => 4,
                        'relation_id'    => 0,
                        'relation_sheet' => 0,
                    ]);
                }
                //店铺积分归零
                $row->points_one = 0;
                $row->save();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
            $this->success('保存成功');
        }
        //当前店铺 积分重新计算
        //统计店铺积分
        //店铺总共发出去的积分数量
        //总共发出的积分
        $sendNum = PointsLog::where('shop_id', $id)
            ->where('type', 'in', [1, 5])
            ->sum('num');

        //总共收入积分
        $incomeNum       = PointsLog::where('shop_id', $id)
            ->where('type', 'in', [2, 4])
            ->sum('num');
        $num             = $incomeNum - $sendNum;
        $row->points_one = $num;

        //统计当前店铺关联的订单号, 并查询这些订单号 有多少是已支付未取货的
        $num2 = PointsLog::alias('pl')
            ->join('pm_order o','pl.relation_id = o.id','left')
            ->where('pl.shop_id',$id)
            ->where('pl.type',2)
            ->where('pl.flag',2)
            ->where('o.pay_status',1)
            ->where('o.status',0)
            ->sum('pl.num');

        $row->save();
        $num3 = $num - $num2;
        $this->assign('send_num', $sendNum);
        $this->assign('income_num', $incomeNum);
        $this->assign('num', $num);
        $this->assign('num2', $num2);
        $this->assign('num3', $num3);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 结算修改 (0901)
     */
    public function settlement2(){
        $param = $this->request->param();
        $rule = [
            'type|类型' => 'require|in:1,2',
            'num|数量' => 'require|number',
            'id|店铺id' => 'require|number',
        ];
        $this->validate($param, $rule);
        $row = $this->model->find($param['id']);
        $num = $param['num'];
        $type = $param['type'];
        Db::startTrans();
        try {
            //店铺增加积分变动记录
            if ($type == 1) {
                //需要补充店铺积分
                //商户增加积分记录
                PointsLog::create([
                    'form_user_id'   => 0,
                    'user_id'        => 0,
                    'shop_id'        => $row->id,
                    'num'            => $num,
                    'type'           => 4,
                    'flag'           => 3,
                    'relation_id'    => 0,
                    'relation_sheet' => 0,
                ]);
                //店铺积分归零
                $row->points_one += $num;
            } else {
                PointsLog::create([
                    'form_user_id'   => 0,
                    'user_id'        => 0,
                    'shop_id'        => $row->id,
                    'num'            => $num,
                    'type'           => 5,
                    'flag'           => 4,
                    'relation_id'    => 0,
                    'relation_sheet' => 0,
                ]);
                $row->points_one -= $num;
            }
            $row->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('结算失败：' . $e->getMessage());
        }
        $this->success('结算成功');
    }
    /**
     * 导出 excel
     * 结算明细
     */
    public function export($id)
    {
        $list                    = PointsLog::with('order_r')
            ->where('shop_id',$id)
            ->limit(100000)
            ->order('id', 'desc')
            ->select();
        foreach($list as &$v){
            switch($v->type){
                case 1: //用户增加
                    $v->type_name = '减少';
                    break;
                case 2: //用户减少
                    $v->type_name = '增加';
                    break;
                case 3: //用户不变
                    $v->type_name = '不变';
                    break;
                case 4: //商户增加
                    $v->type_name = '增加';
                    break;
                case 5: //商户减少
                    $v->type_name = '减少';
                    break;
                default:
                    $v->type_name = '异常';
                    break;
            }
            switch($v->flag){ //1:商家赠送 2:兑换商品 3:商家结算 4:商家提现  5:商家退款
                case 1:
                    $v->flag_name = '商家赠送';
                    break;
                case 2:
                    $v->flag_name = '兑换商品';
                    break;
                case 3:
                    $v->flag_name = '商家结算';
                    break;
                case 4:
                    $v->flag_name = '商家结算';
                    break;
                case 5:
                    $v->flag_name = '商家退款';
                    break;
                default:
                    $v->flag_name = '异常';
                    break;
            }
//            $v->create_time = date('Y-m-d H:i:s',$v->create_time);
        }
        $fileName = date('YmdHis');

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(public_path() . '订单导出模板.xls');
        $sheet       = $spreadsheet->getActiveSheet();
        $startLine   = 2;
        $line        = $startLine;
        foreach ($list as $k => $l) {
            $sheet->setCellValue('A' . $line, $l['num']);
            $sheet->setCellValue('B' . $line, $l['type_name']);
            $sheet->setCellValue('C' . $line, $l['flag_name']);
            $sheet->setCellValue('D' . $line, isset($l->order_r)?$l->order_r->order_no:'');
            $sheet->setCellValue('E' . $line, $l['user_id']);
            $sheet->setCellValue('F' . $line, $l['create_time']);
            $sheet->setCellValue('G' . $line, $l['shop_id']);
            $line++;
        }
        // Redirect output to a client’s web browser (Xls)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="订单-' . $fileName . '.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->save('php://output');
        exit;
    }
}